package com.song.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.song.api.BaseService;
import com.song.enums.UserStatus;
import com.song.exception.GraceException;
import com.song.grace.result.ResponseStatusEnum;
import com.song.pojo.AppUser;
import com.song.user.mapper.AppUserMapper;
import com.song.user.service.AppUserMngService;
import com.song.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class AppUserMngServiceImpl extends BaseService implements AppUserMngService {

    @Autowired
    private AppUserMapper appUserMapper;

    /**
     * 分页查询用户管理列表
     *
     * @param nickname
     * @param status
     * @param startDate
     * @param endDate
     * @param page
     * @param pageSize
     */
    @Override
    public PagedGridResult queryAppUserList(String nickname, Integer status, Date startDate, Date endDate, Integer page, Integer pageSize) {

        Example example = new Example(AppUser.class);
        example.orderBy("createdTime").desc();
        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotEmpty(nickname)) {
            criteria.andLike("nickname", "%" + nickname + "%");
        }

        if (UserStatus.isUserStatusValid(status)) {
            criteria.andEqualTo("activeStatus", status);
        }

        if (startDate != null) {
            criteria.andGreaterThanOrEqualTo("createdTime", startDate);
        }
        if (endDate != null) {
            criteria.andLessThanOrEqualTo("createdTime", endDate);
        }

        PageHelper.startPage(page, pageSize);

        List<AppUser> list = appUserMapper.selectByExample(example);

        return setPagedGridResult(list, page);
    }

    /**
     * 冻结用户，或解除封号
     *
     * @param userId
     * @param doStatus
     */
    @Transactional
    @Override
    public void freezeUserOrNot(String userId, Integer doStatus) {
        AppUser appUser = new AppUser();
        appUser.setId(userId);
        appUser.setActiveStatus(doStatus);
        int result = appUserMapper.updateByPrimaryKeySelective(appUser);
        if (result != 1) {
            GraceException.display(ResponseStatusEnum.USER_UPDATE_ERROR);
        }
    }
}
